const express = require('express');
const userService = require('../services/userService');
const cookiesParser = require('cookie-parser');
const cookieSession = require('cookie-session');

var router = express.Router();

router.post('/register',async (req,res,next)=> {
    var user = req.body;
    console.log(user);
    if(user==undefined||user=={}||user==[]){
        // return {success:false,msg:'用户名不能为空'};
        res.send({success:false,msg:'用户名与密码不能为空'});
    }else{
        let data = await userService.addUser(user);
        console.log('userService');
        console.log(data);
        if(data.success){
            //注册成功
            console.log('router注册成功！');
            res.send({success:true,user:data.user})
            return 'aaa';

        }else{
            console.log('router注册失败！');
            return data;

        }
    }
});

router.post('/login',async (req,res,next)=>{
    var user = req.body;
    // var cookies = req.cookies;
    console.log(user);
    if(user==undefined||user=={}||user==[]){
        // return {success:false,msg:'用户名不能为空'};
        res.send({success:false,msg:'用户名与密码不能为空'});
    }else{
        var data = await userService.login(user);
        //登录成功，要进行session与cookie
        if(data.success){
            //登陆成功，对cookie进行操作，同时也对session进行操作
            if(user.remeber=='true'){
                res.cookie('user',data.user,{maxAge:7*24*60*60*1000});
            }
            req.session.user = data.user;
            //登录之后立即记录
        };
            res.send(data);
    }
})

router.use('/logout',(req,res)=>{
    var user = req.session['user'];
    if(user==null||user=={}||user==undefined){
        res.send('Hava not login in...');
    }else{
        res.session.destroy();
        res.send('views/index/html');
    }
})
exports.router = router;